package in.iqing.view.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.squareup.otto.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import in.iqing.app.R;
import in.iqing.base.BaseActivity;
import in.iqing.control.adapter.DirectoryAdapter;
import in.iqing.control.api.ApiHelper;
import in.iqing.control.api.callback.VolumeCallback;
import in.iqing.control.helper.EventHelper;
import in.iqing.control.helper.LogHelper;
import in.iqing.control.util.IntentUtil;
import in.iqing.model.bean.Book;
import in.iqing.model.bean.DirectoryItem;
import in.iqing.model.bean.Chapter;
import in.iqing.model.bean.History;
import in.iqing.model.bean.Volume;
import in.iqing.model.db.DBHelper;
import in.iqing.module.download.ChapterTask;
import in.iqing.module.download.DownloadManager;
import in.iqing.view.widget.SimpleDividerItemDecoration;

/**
 * Created by ZuoShu on 15/7/9.
 */
public class DirectoryActivity extends BaseActivity {
    private Book book;

    @Bind(R.id.title)
    TextView title;

    @Bind(R.id.directory_recycler)
    RecyclerView directoryRecylerView;

    @Bind(R.id.cache_menu)
    ImageView cacheMenu;

    @Bind(R.id.cache_layout)
    View cacheLayout;

    @Bind(R.id.cache_text)
    TextView cacheText;

    @Bind(R.id.start_download)
    ImageView startDownload;

    @Bind(R.id.stop_download)
    ImageView stopDownload;

    @Bind(R.id.download_progress)
    ProgressBar progress;

    @Bind(R.id.delete_cache)
    ImageView deleteCache;

    private DirectoryAdapter directoryAdapter;

    private List<Chapter> chapters;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_directory);
    }

    @Override
    protected void onInitialize(Bundle savedInstanceState) {
        super.onInitialize(savedInstanceState);
        book = (Book) getIntent().getSerializableExtra("book");
        title.setText(book.getTitle());
        cacheText.setText(getString(R.string.activity_directory_cache_text, book.getTitle()));
        setRecyclerView();
        initDownloadStatus();
        loadDirectory();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventHelper.getSingleton().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventHelper.getSingleton().unregister(this);
    }

    private void setRecyclerView() {
        directoryAdapter = new DirectoryAdapter();
        directoryRecylerView.setAdapter(directoryAdapter);
        directoryRecylerView.setLayoutManager(new LinearLayoutManager(getContext()));
        directoryRecylerView.addItemDecoration(new SimpleDividerItemDecoration(getContext()));
        directoryAdapter.setListener(new ExtChapterClickListener());
        History bookmark = DBHelper.getInstance().getBookmark(book.getId());
        if (bookmark != null) {
            directoryAdapter.setLastReadChapterId(bookmark.getChapterId());
        }
    }

    private void initDownloadStatus() {
        Book dbBook = DBHelper.getInstance().findFirstById(Book.class, book.getId());
        if (dbBook != null) {
            progress.setMax(dbBook.getChapterCount());
            progress.setProgress(dbBook.getCachedChapterCount());
            deleteCache.setEnabled(dbBook.getCachedChapterCount() > 0);
            cacheText.setTextColor(dbBook.getCachedChapterCount() > 0
                    ? getResources().getColor(R.color.white)
                    : getResources().getColor(R.color.theme));
        }
        directoryAdapter.clearDownloadChapters();
        directoryAdapter.addDownloadedChapters(DBHelper.getInstance().getDownloadedChapters(book));
        directoryAdapter.notifyDataSetChanged();
    }

    private void resetDownloadStatus() {
        progress.setProgress(0);
        deleteCache.setEnabled(false);
        directoryAdapter.clearDownloadChapters();
        directoryAdapter.notifyDataSetChanged();
        stopDownload.setVisibility(View.GONE);
        startDownload.setVisibility(View.VISIBLE);
    }

    private void updateDownloadStatus(DownloadManager.DownloadEvent.DownloadChapterFinish chapterFinish) {
        Book dbBook = DBHelper.getInstance().findFirstById(Book.class, book.getId());
        if (dbBook != null) {
            progress.setMax(dbBook.getChapterCount());
            progress.setProgress(dbBook.getCachedChapterCount());
            deleteCache.setEnabled(dbBook.getCachedChapterCount() > 0);
            if (dbBook.getCachedChapterCount() >= dbBook.getChapterCount()) {
                LogHelper.warn(TAG, "all chapter finish book:" + book.getId() + " " + book.getTitle());
                startDownload.setVisibility(View.VISIBLE);
                startDownload.setEnabled(false);
                stopDownload.setVisibility(View.GONE);
                cacheLayout.setVisibility(View.GONE);
            }
        }
        directoryAdapter.addDownloadedChapter(chapterFinish.chapterId);
        directoryAdapter.notifyDataSetChanged();
    }

    private void loadDirectory() {
        ApiHelper.getSingleton().getVolume(VOLLEY_TAG, book.getId(), new ExtQingVolumeCallback());
    }

    @OnClick(R.id.back)
    public void onBackClick(View v) {
        finish();
    }

    @OnClick(R.id.start_download)
    public void onStartCacheClick(View v) {
        DBHelper.getInstance().saveBook(book);
        DownloadManager.getInstance().start(book);
        startDownload.setVisibility(View.GONE);
        stopDownload.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.stop_download)
    public void onStopDownloadClick(View v) {
        DownloadManager.getInstance().stop(book);
        stopDownload.setVisibility(View.GONE);
        startDownload.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.cache_menu)
    public void onCacheMenuClick(View v) {
        cacheLayout.setVisibility(cacheLayout.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
    }

    @Subscribe
    public void onDownload(DownloadManager.DownloadEvent.DownloadChapterFinish chapterFinish) {
        ChapterTask chapterTask = DBHelper.getInstance().getChapterTask(chapterFinish.chapterId);
        LogHelper.warn(TAG, "onDownload:" + chapterTask.toString());
        updateDownloadStatus(chapterFinish);
    }

    @OnClick(R.id.delete_cache)
    public void onDeleteCacheClick(View v) {
        DownloadManager.getInstance().delete(book);
        resetDownloadStatus();
    }

    private class ExtQingVolumeCallback extends VolumeCallback {

        @Override
        public void onStart() {
            showLoading();
        }

        @Override
        public void onSuccess(List<Volume> volumes) {
            if (volumes == EMPTY) {
                showEmpty();
                return;
            }

            List<DirectoryItem> directoryItems = new ArrayList<>();
            chapters = new ArrayList<>();
            for (Volume volume : volumes) {
                directoryItems.add(DirectoryItem.fromVolume(volume));
                if (volume.getChapters() != null && volume.getChapters().size() > 0) {
                    for (Chapter chapter : volume.getChapters()) {
                        directoryItems.add(DirectoryItem.fromChapter(chapter));
                        chapters.add(chapter);
                    }
                }
            }

            DBHelper.getInstance().saveBookDirectory(book, volumes);
            showContent();
            cacheMenu.setVisibility(View.VISIBLE);
            directoryAdapter.setDirectoryItems(directoryItems);
            directoryAdapter.notifyDataSetChanged();
        }

        @Override
        public void onFailure(int code, String msg) {
            showEmpty();
        }
    }

    private class ExtChapterClickListener implements DirectoryAdapter.OnChapterClickListener {

        @Override
        public void onChapterClick(DirectoryItem chapter) {
            Chapter qingChapter = chapter.getChapter();

            Bundle extra = getIntent().getExtras();
            extra.putSerializable("chapter", qingChapter);
            extra.putSerializable("chapters", (Serializable) chapters);
            extra.putSerializable("book", book);
            extra.putBoolean("from_chapter", true);
            IntentUtil.startActivity(getActivity(), ContentActivity.class, extra);
        }
    }
}
